<template>
  <div style="position:relative">
    <div class="guding">
      <!-- 项目信息 -->
      <van-cell-group>
			  <van-field label=" 项目点名称" v-model="projectVal" placeholder="请选择项目点" input-align="right" required :is-link="true" readonly style="margin-top:1px;" @click="show=true"/>
		  </van-cell-group>
      <van-action-sheet v-model="show" :actions="actions" @select="onSelect" />
    </div>
    <!-- 1、建筑列表 默认状态-->
    <div style="background:#fff">
      <div style="height:54px"></div>
      <!-- 2、建筑列表 编辑状态-->
      <div style="padding:0 3% 0 3%;">
        <van-row type="flex" class="cellHeight" v-for="(item, index) in buildingsVal" :key="index">
          <van-col span="22" style="font-size:18px;" @click="toFloor(item)">
            <span :class="item.status == 1 ? 'openColor':'closeColor'"> {{item.name}}</span>
            <!-- {{item.name}} -->
          </van-col>
          <van-col span="2" style="display:flex">
            <van-checkbox v-model="item.show" icon-size="16px" style="margin-left:13px;margin-top:2px" max="1" @click="selectData(item, index)"></van-checkbox>
          </van-col>
        </van-row>
     </div>
    </div>
    <!-- 底部按钮 -->
    <div style="height:82px"></div>
    <div class="paddi">
      <div style="display: flex;" v-if="edieBtnShow">
        <van-button color="#08395b" :block="true" class="btn" :disabled="!openDisabled" width="50%" @click="openStatus">{{openclose}}</van-button>
        <div style="width:6px"></div>
        <van-button color="#08395b" :block="true" class="btn" :disabled="editDisabled" width="50%" @click="toEdit">编辑</van-button>
      </div>

      <van-button color="#08395b" :block="true" class="btn" :to='{path: "/addbuildings"}' :disabled="addDisabled" width="50%" v-if="addBtnShow">添加建筑</van-button>
    </div>
    <!-- 数据为空显示 -->
    <!-- <van-loading type="spinner" color="#09385B" v-if="loadingShow" style="position:absolute; top:40%; left:46%"/> -->
    <pro-kong v-if="conentShow"></pro-kong>
  </div>
</template>
<script>
import proKong from "../components/projectKong.vue"
export default {
  components:{
    proKong,
  },
  data(){
    return{
      arr: [], //选中的列表数组坐标
      selectNum: 0,  //选中个数
      openclose:'启用', //启用停用按钮切换
      edieBtnShow: false, // 编辑 添加按钮显示 否
      addBtnShow:false, //添加按钮显示
      checked: true,
      popup:false, //选择弹窗开关
      show:false,
      actions: [],
      openDisabled: false, //启用 编辑 按钮开关
      editDisabled: false, //编辑 按钮开关
      addDisabled: false,
      // loadingShow: true, 
      conentShow:false,  //页面为空显示  控制
      projectVal: sessionStorage.getItem('ProName'),
      from:{
        result: [],
        projectVal: 11,
      },
      //1、项目点数据
      option1: [
        // { text: '复旦软件园', value: 0 },
        // { text: '陆家嘴金融中心', value: 1 },
        // { text: '中心', value: 2 },
      ],

      //2、建筑
      buildingsVal: [
        // {id:1, name:'华荣大厦1'},
      ],
    }
  },
  methods:{
    //启用\停用
    openStatus(){
      this.$dialog.confirm({
        title: '提示信息',
        message: `确定要${this.openclose}建筑信息吗？`
      }).then(() => {
        //多条数据启用 停用 循环调接口
        this.arr.forEach(el =>{
          this.OpenandClose(this.buildingsVal[el].id, this.buildingsVal[el].status);
        });
      }).catch(() => {
      // on cancel
      });
    },

    //列表右侧 选择 控制
    selectData(val, index){
      //思路 选中（等于true）的列表 添加到数组中,  等于false 删除该数组  
      if(!(val.show)){ 
        //this.arr[index] = index; //添加 选中坐标 给数组
        this.arr.push(index);
      }else{
        this.arr.splice(this.arr.findIndex(item => item === index), 1);
        // this.arr.splice(index, 1);
      }
      if(this.arr.length > 0){this.checkedStatus(this.arr[0]) } //启用 还是 停用
      
      if(this.arr.length >= 1){
        this.edieBtnShow = true; //启用 编辑 按钮显示
        this.addBtnShow = false; //添加 按钮 隐藏
        
        if(this.arr.length == 1){ //编辑按钮 选长度 等于 1  启用
          this.editDisabled = false;
        }else{
          this.editDisabled = true;
        }
      }else{
        this.edieBtnShow = false; //启用 编辑 按钮隐藏
        this.addBtnShow = true; //添加按 钮显示
      }
      //选中的单挑数据存在 sessionStorage
      sessionStorage.setItem("buildID", val.id);  //建筑类别ID
      sessionStorage.setItem("buildVal", JSON.stringify(val));//选中的建筑信息
    },
    //选中编辑
    toEdit(){
      if(this.arr.length == 1 ){
        let $index = this.arr[0]; //选中数据坐标
        let buildVal = this.buildingsVal[$index]; //选中数据
        sessionStorage.setItem("buildID", buildVal.id);  //建筑类别ID
        sessionStorage.setItem("buildVal", JSON.stringify(buildVal)); //选中的建筑
         this.$router.push({path: "/eidtbuildings"});
      }else{
        console.log('选择出错有误');
      }
    },
    // 判断按钮 显示文字 启用 还是 停用
    checkedStatus(index){
      //判断按钮显示文字
      if(this.buildingsVal[index].status==2){
        this.openclose="启用";
      }else{
        this.openclose="停用";
      }
      let arr2 = [];
      this.arr.forEach(el =>{
        this.buildingsVal[el].status
        arr2.push(this.buildingsVal[el].status);
      });
      this.openDisabled = this.isAllEqual(arr2);
      // this.isAllEqual(arr2)
    },
    //判断数组是否重复
    isAllEqual(array) {
      if (array.length > 0) {
        return !array.some(function(value, index) {
          return value !== array[0];
        });
      } else {
        return true;
      }
    },
    //启用编辑接口
    OpenandClose(BuidIDs, StatusVal){
      let data = {
        id: parseInt(BuidIDs),
        status: parseInt(StatusVal) == 1 ? 2 : 1,
      } 
      this.$http.put("/api/buildings/status", data, {
        headers:{ 'Authorization':localStorage.getItem('token'),}
      }).then(res =>{
          if(res.data.errcode == 0){
            // this.$router.go(0);
            this.getbuildList(sessionStorage.getItem('ProID'));
            this.$toast.success('操作成功！');
            this.edieBtnShow = false; //确认完操作 隐藏 操作栏
            this.addBtnShow = true; //添加按钮显示
          }else{
            this.$toast.fail('操作失败！');
          }
      })
    },

    closeShow(){
      this.popup = false;
    },
    //点选项目
    onSelect(item) {
      this.projectVal = item.name;
      this.getbuildList(item.value);
      sessionStorage.setItem('ProName', item.name);
      sessionStorage.setItem('ProID', item.value);
      
      this.show = false;
      this.buildingsVal = [];//切换项目清空上一个建筑数据
      this.addBtnShow = true;
    },
    // 获取项目点数据 更新建筑点数据
    getProjectList(){
      let Arr = JSON.parse(localStorage.getItem('locatRoles'));
      let roleArr = [];
      if(Arr != null){
       Arr.forEach(el =>{
          roleArr.push(parseInt(el));
        })
      }
      let roles2 = [40];
      let roles3 = roles2.join(",");
      this.$http({
        url: '/api/locations/getLocationAndRoleList',
        method: 'get',
        headers:{Authorization: localStorage.getItem("token")},
        params: {
          userId: localStorage.getItem('userid'),
          // roles: roleArr.join(),
          roles: roles3,
          limit: 999,
          page: 0,
        }
      }).then(res =>{
        if(res.data.errcode == 0){
          if(res.data.data.length == 0){
            this.show = false;
            this.$toast.fail('项目点为空');
            return;
          }
          if(res.data.data.length == 1){
            this.projectVal = res.data.data[0].name;
            sessionStorage.setItem('ProName',res.data.data[0].name);
            sessionStorage.setItem('ProID',res.data.data[0].id);
            this.getbuildList(res.data.data[0].id);
          }
           res.data.data.forEach(el => {
            this.actions.push({name: el.name, value:el.id});
          });
          }
      }).catch(err =>{console.log({err})});
    },

    //获取建筑点数据
    getbuildList(projectVal){ 
      if(projectVal!=null){
       this.$http.get(`/api/buildings/getBuildingsList?locationId=${projectVal}&limit=999&page=1`,{
        headers:{ 'Authorization':localStorage.getItem('token'),}
      }).then(res =>{
        if(res.data.errcode == 0){
          if(res.data.data.list.length == 0){
            // this.loadingShow = false
            this.$toast.fail('建筑数据为空');
            this.conentShow = true;
          }else{
            // this.loadingShow = false
            this.conentShow = false;
            this.buildingsVal = [];
            res.data.data.list.forEach(el => {
            this.buildingsVal.push(
              {
                name: el.name,
                id:el.id,
                description: el.description,
                mainphone: el.mainphone,
                buildingClassId: el.buildingClassId,
                buildingClass: el.buildingClass,
                status: el.status,
                locationId: el.locationId,
                show: false,
              });
            });
          }
        }
      })
      }else{
        console.log('建筑ID为空');
      }
      this.arr = [];
    },
    // 保存
    save(){
      this.$toast('保存成功');
    },
    toggle1(val){
      sessionStorage.setItem("buildID", val.id); //点击选中的 建筑ID  存储
      sessionStorage.setItem("buildVal", JSON.stringify(val));//选中的建筑信息 存储
      this.popup = true;
    },
    // 跳转楼层
    toFloor(val){
      sessionStorage.setItem("buildID", val.id); //点击选中的 建筑ID  存储
      sessionStorage.setItem("buildVal", JSON.stringify(val));//选中的建筑信息 存储
      this.$router.push({
        path: `/floor`, //进入下级
      })
    },
    //跳转编辑
    toBulidEdit(){
      this.$router.push({path: '/eidtbuildings'});
    },
  },
  created(){
    setTimeout(res=>{
      this.getProjectList();
    }, 800)
    this.getbuildList(sessionStorage.getItem('ProID'));
    this.projectVal = sessionStorage.getItem('ProName');
    if(this.projectVal){
      this.addBtnShow = true;
    }
    
  }
}
</script>

<style>
  .van-button{
    width: 100%
  }
  .van-cell{
    padding: 23px;
  }
  .van-ellipsis {
    font-weight: 600;
  }
 .van-dropdown-menu__title {
    color:#333;
    font-size: 35px;
    
  }
  .van-dropdown-menu__item {
    justify-content: flex-start;
    margin-left: 5px;
  }
  /* 添加建筑 */
  .addjianzhu{
    background:#fff;
    display: flex;
    font-size: 28px;
    justify-content:flex-end;
    align-items: center;
    height: 97px;
    margin-top:1px;
  }
  .van-cell__title{
    color: #323232;
    font-size: 33px;
    font-weight: bold;
  }
  /* 固定底部按钮 */
  .bottom_btn{
    width: 96%;
    position: fixed;
    bottom: 0;
    left: 4%;
    overflow: hidden;
  }
  .guding{
    border-bottom: 1px solid #f3f3f3;
    width: 100%;
    z-index: 99;
    position: fixed;
    left: 0;
    top: 0;
  }
  .paddi{
    background: #fff;
    padding: 2% 3%;
    position:fixed;
    left:0;
    bottom:0%;
    width: 100%;
    display: flex;
    align-content: center;
    flex-direction: column;
    justify-content: center;
    /* margin: 0 auto; */
  }
  .btn{
    font-size: 32px;
    width:100%; 
    margin:11px auto; 
    border-radius:8px;
  }
  .openColor{
    color: #08395A !important;
  }
  
  .cellHeight{
    margin-top:2px;
    /* padding:28px 0; */
    border-bottom:1px solid #EDEDED;
    color:#474747;
    /* background:red; */
    height:95px;
    line-height:95px;
  }
  .btn_to{
    display: flex;
    margin-bottom: 24px;

  }
</style>